package main.java.反射5;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther:Liu
 * @Testname:Mydbuse
 * @Date:2025/3/13 15:35
 */
public class Mydbuse {

    //查找
    public static <T> List<T> findList(String sql, Class<T> c) throws Exception {
        /**
         * 连接
         */
        ArrayList<T> arrayList = new ArrayList<>();
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "123456");
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();//返回结果集
        /**
         * 获取数据
         */
        ResultSetMetaData metaData = resultSet.getMetaData(); //获取原数据
        int columnCount = metaData.getColumnCount(); //获取列数
        //解析结果集
        while (resultSet.next()) {
            T t = c.newInstance();//封装成对象
            for (int i = 1; i <= columnCount; i++) {
                Object value = resultSet.getObject(i);//获取列数据
                String columnName = metaData.getColumnName(i);//获取表字段名
                Field declaredField = c.getDeclaredField(columnName);//属性名
                declaredField.setAccessible(true);
                declaredField.set(t, value);
            }
            arrayList.add(t);
        }
        return arrayList;
    }

    //插入
//    public static boolean insertList(String sql,Object obj)throws Exception{
//        Class.forName("com.mysql.cj.jdbc.Driver");
//        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC", "root", "123456");
//        Statement statement = conn.createStatement();
//        int i = statement.executeUpdate(sql);
//
//        StringBuffer STR1=new StringBuffer("")
//    }
}
